// pages/goods_detail/goods_detail.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canScroll: true,
    goods_info: null,
    current: 0,
    buyTime: {
      hour: '01',
      min: '00',
      sec: '00'
    },
    offShelf: false,//商品是否下架
    isBuying: false, //正在购买
    networkConnected: true,  //网络连接正常
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.goods_id = options.goods_id;
    this.group_id = options.group_id || 0;
    this.setData({
      pageHeight: app.globalData.pageHeight - 108,
    })

    this.loadPageData();
    // this.buyTimeCountdown(3600);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取用户信息
    this.getMyInfo();
  },

  /**
   * 加载页面数据
   */
  loadPageData: function () {
    //获取商品信息
    this.getGoodsInfo();
    //生成分享码
    this.getShareToken();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var shareType;
    var path = '/pages/login/login';
    if (e && e.from == 'button') {
      shareType = e.target.dataset.type;
      if (this.shareToken) {
        path += '?token=' + this.shareToken;
      }
    }
    // console.log(path)
    return {
      title: '【' + this.data.myinfo.user_name + '】，0元拼团，1分钱不要，全场包邮>>',
      path: path,
      success: () => {
        if (shareType == 'goods') {
          app.Ajax({
            method: 'POST',
            url: '/api/index.php?app=home&act=share',
            data: {
              type: shareType
            },
            success: (res) => {
              this.messageToast('分享成功，获得' + res.stars + '星星');
              //更新用户星星
              this.getMyInfo();
            },
            fail: (err) => {
              this.messageToast('已到达分享上限');
            }
          })
        }
      }
    }
  },

  /**
   * 用户信息
   */
  getMyInfo: function () {
    app.getUserInfo((res) => {
      this.setData({
        myinfo: res
      })
    })
  },

  /**
   * 获取商品详情
   */
  getGoodsInfo: function () {
    app.Ajax({
      url: '/api/index.php?app=goods&act=detail',
      data: {
        goods_id: this.goods_id,
        group_id: this.group_id,
      },
      success: (res) => {
        if (res.awards.code == 0) {
          this.setData({
            goods_info: res
          })
          this.messageToast("浏览新商品，获得" + res.awards.data.stars + "星星");
        } else {
          this.setData({
            goods_info: res
          });
        }
      },
      fail: (err, code) => {
        if (code == 10001) {
          this.setData({
            offShelf: true
          })
          return
        }
        if (app.globalData.isConnected === false) {
          this.setData({
            networkConnected: false
          })
        } else {
          this.messageToast(err);
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 2000);
        }
      }
    })
  },

  /**
   * 生成分享码
   */
  getShareToken: function () {
    app.Ajax({
      method: 'POST',
      url: '/api/index.php?app=home&act=token',
      data: {
        type: 0,
        page: 'pages/goods_detail/goods_detail?group_id=' + this.group_id + '&goods_id=' + this.goods_id,
      },
      success: (res) => {
        this.shareToken = res.token;
      }
    })
  },

  /**
   * 封面图片切换
   */
  coverImgChange: function (e) {
    var current = e.detail.current;
    this.setData({
      current: current
    })
  },

  /**
   * 返回首页
   */
  backToHome: function () {
    wx.switchTab({
      url: '../homepage/homepage',
    })
  },

  /**
   * 收藏商品（取消收藏）
   */
  collectGoods: function (e) {
    var status = e.currentTarget.dataset.status;
    app.Ajax({
      url: '/api/index.php?app=goods&act=collection',
      data: {
        goods_id: this.goods_id,
        fav_status: status,
      },
      success: (res) => {
        if (status == 0) {
          this.setData({
            'goods_info.fav_status': status,
          })
          this.messageToast('收藏成功！');
        } else {
          this.setData({
            'goods_info.fav_status': status,
          })
          this.messageToast('收藏已取消');
        }
      },
      fail: (err) => {
        this.messageToast('操作失败');
      }
    })
  },

  /**
   * 立即购买
   */
  goodsBuy: function () {
    this.setData({
      isBuying: true,
      canScroll: false,
    })
  },

  /**
   * 取消购买
   */
  buyCancel: function () {
    this.setData({
      isBuying: false,
      canScroll: true,
    })
  },

  /**
   * 玩购抓取
   */
  goodsPlay: function () {
    //如果射娃娃页面已经存在，则直接回退到射娃娃页面
    var pages = getCurrentPages();
    var delta;
    for (var i = 1; i <= pages.length; i++) {
      if (pages[pages.length-i].route == 'pages/game/shoot/shoot') {
        delta = i;
      }
    }
    if (delta) {
      wx.navigateBack({
        delta: delta-1
      })
      return;
    }

    //如果射娃娃页面不存在，则进行条件判断再打开射娃娃页面
    var goods_info = this.data.goods_info;
    //星星不足
    if (goods_info.stars < goods_info.play_price) {
      this.messageToast('您的星星不足');
      return;
    }
    //默认用商品的第一个sku，如果没有库存，则再找第二个
    var goodsIdx = 0;
    var sku_id = null;
    while (sku_id == null && goodsIdx < goods_info.skus.length) {
      if (goods_info.skus[goodsIdx].stock > 0) {
        sku_id = goods_info.skus[goodsIdx].sku_id;
      }
      goodsIdx++;
    }
    //没有库存
    if (sku_id == null) {
      this.messageToast('商品库存不足，请选择其他商品');
      return;
    }
    // wx.navigateTo({
    //   url: '../room/room?goods_id=' + this.goods_id + '&sku_id=' + sku_id,
    // })
    wx.navigateTo({
      url: '../game/shoot/shoot?goods_id=' + this.goods_id + '&sku_id=' + sku_id,
    })
  },

  /**
   * 立即兑换
   */
  exchangeGoods: function () {
    if (this.data.goods_info.star_price > this.data.goods_info.stars) {
      this.messageToast('您的星星不足！');
    } else {
      this.setData({
        isBuying: true,
        canScroll: false,
      })
    }
  },

  /**
   * 开团兑换
   */
  goodsGroupExchange: function () {
    if (this.data.goods_info.spell_stars > this.data.goods_info.stars) {
      this.messageToast({
        image: {
          url: 'style/img/icon/star_short.png',
          width: 176,
          height: 176,
        },
        title: '参与失败',
        content: '你的星星余额不足，开团失败',
        cancelText: '暂时放弃',
        confirmText: '做任务赚星星',
      }, 2);
    } else {
      this.setData({
        isBuying: true,
        canScroll: false,
      })
    }
  },

  /**
   * 星星不足，去做任务
   */
  goTask: function() {
    wx.switchTab({
      url: '../task/task',
    })
  },

  /**
   * 抢购倒计时
   */
  buyTimeCountdown: function (buyTime) {
    var self = this;
    timeCountdown(buyTime);
    var timeInterVal = setInterval(() => {
      timeCountdown(--buyTime);
      if (buyTime == 0) {
        clearInterval(timeInterVal);
      }
    }, 1000);
    function timeCountdown(buyTime) {
      var hour = '0' + parseInt(buyTime / 3600);
      var min = parseInt((buyTime - 3600 * hour) / 60) + '';
      if (min.length < 2) {
        min = '0' + min;
      }
      var sec = buyTime - 3600 * hour - 60 * min + '';
      if (sec.length < 2) {
        sec = '0' + sec;
      }
      var time = {
        hour: hour,
        min: min,
        sec: sec
      }
      self.setData({
        buyTime: time
      })
    }
  },

  /**
   * 消息提示
   */
  messageToast: function (param, toastType) {
    toastType = toastType || 0;
    if (toastType == 0) {
      this.setData({
        toastType: 0,
        message: param
      })
    } else if (toastType == 2) {
      this.setData({
        toastType: 2,
        modalOptions: param
      })
    }
  },
})